package com.woniu.inlet.timer;

import com.woniu.adapter.DailyIncomeAdapter;
import com.woniu.adapter.HoldProductAdapter;
import com.woniu.adapter.PersonalIncomeAdapter;
import com.woniu.outlet.mysql.po.HoldProductMySQL;
import com.woniu.outlet.mysql.po.PersonalIncomeMySQL;
import com.woniu.outlet.redis.CodeOneRedisDao;
import com.woniu.outlet.redis.CodeTwoRedisDao;
import com.woniu.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 每日计算收益定时任务
 */
@Component
@Slf4j
public class DailyIncomeTimer {

    @Autowired
    private PersonalIncomeAdapter personalIncomeAdapter;

    @Autowired
    private DailyIncomeAdapter dailyIncomeAdapter;

    @Autowired
    private CodeOneRedisDao oneRedisDao;

    @Autowired
    private HoldProductAdapter holdProductAdapter;


    /**
     * "0 30 1 ? * *" 每日1:30点计算收益
     *
     */
    @Scheduled(cron = "0 30 1 ? * *")
    public void currentIncome() {
        log.debug("[计算收益]定时任务开始，当前时间{}",DateUtil.getBuyTime());
        //获取所有单子
        List<PersonalIncomeMySQL> status0 = personalIncomeAdapter.getAllStatus_0();
        //生成每日收益
        for (PersonalIncomeMySQL p : status0) {
            //计算每日收益和生成收益记录
            BigDecimal income = dailyIncomeAdapter.insert(p);
            //计算总收益
            p.setTotalIncome(p.getTotalIncome().add(income));
            //得到净值 T-1
            BigDecimal tv = oneRedisDao.findById(p.getCodeId()).orElseThrow(NullPointerException::new).getTodayValuation();
            p.setTodayValuation(tv.toString());
            //更新收益
            personalIncomeAdapter.updateIncome(p);
        }
        log.debug("更新每条收益成功，共更新{}条收益",status0.size());
        log.debug("[计算收益]定时任务结束");

    }
}
